function getNickName(name) {

    //定义一个表情包正则
    name = name.trim();
    let emojiReg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;
    return name.replace(emojiReg, "");

}


function isIP(ip) {
    var re = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    return re.test(ip);
}


function createList(pageNo = 1, pageSize = 10) {
    let matchData = {
        'isRobot': true,
        'unionID': {
            "$eq": 0
        }
    };
    var start = (pageNo - 1) * pageSize;
    apiAdminGetRecord("userModel", start, pageSize, matchData, function (data) {
        if (data.code === 0) {
            setTimeout(() => {
                $('#robotData').bootstrapTable('load', data.msg);
            }, 200)

        }
    });
}


function robotEdit(info = null) {

    if (info) {

        $("#labelUserID").val(info._id);
        $("#lableUID").val(info.uid);
        $("#lableUID").attr("disabled", "true");
        $("#labelNickname").val(info.nickname);
        $("#labelUnion").val(info.unionID);
        $("#labelUnion").attr("disabled", "true");
        $("#labelWinRate").val(info.winRate);
        $("#labelWinType").val(info.winType);
        $("#labelAddress").val(info.location);
        $("#labelType").val(info.robotType);
        $("#labelGameType").val(info.gameType);
        $("#labelIP").val(info.lastLoginIP);
        if (info.address) {
            $("#labelLatitude").val(JSON.parse(info.address)["x"]);
            $("#labelLongitude").val(JSON.parse(info.address)["y"]);
        }
        if (info.avatar) {
            let imageArr = [info.avatar.replace('/', '')];
            fileOptIcon.originalFileList = imageArr;
        }
        $("#imgArr").empty();
        $("#imgArr").initUpload(fileOptIcon);


    } else {

        $("#labelUserID").val("");
        $("#lableUID").val("");
        $("#lableUID").attr("disabled", false);
        $("#labelNickname").val("");
        $("#labelUnion").val("");
        $("#labelUnion").attr("disabled", false);
        $("#labelWinRate").val("");
        $("#labelWinType").val("");
        $("#labelAddress").val("");
        $("#labelLatitude").val("");
        $("#labelLongitude").val("");
        $("#labelIP").val("");
        fileOptIcon.originalFileList = [];
        $("#imgArr").empty();
        $("#imgArr").initUpload(fileOptIcon);
    }

    $('#addNew').modal('show');

}


function addType() {

    var row = $("#robotData").bootstrapTable('getSelections');
    if (row.length > 0) {
        let list = [];
        for (let i = 0; i < row.length; i++) {
            list.push(row[i].uid);
        }
        $("#reAddUserID").val(list);
        $("#reAddUserID").attr("disabled", true);
        $('#addType').modal('show');
    } else {

        $.modal({
            body: '请先选择机器人'
        });
    }
}


function addOrder() {

    var row = $("#robotData").bootstrapTable('getSelections');
    if (row.length > 0) {
        let list = [];
        for (let i = 0; i < row.length; i++) {
            list.push(row[i].uid);
        }
        $("#addUserID").val(list);
        $("#addUserID").attr("disabled", true);
        $('#addOrder').modal('show');
    } else {
        $.modal({
            body: '请先选择机器人'
        });
    }
}


function addRobotToUnionMu() {

    let uid = $("#addUserID").val();
    let gameType = $("#addUnionID").val();
    $('#addOrder').modal('hide');
    apiRobotToUnion(uid, gameType, () => {
        createList(1);
    });
}

function addRobotToGameType() {

    let uid = $("#addUserID").val();
    let gameType = $("#addUnionID").val();
    $('#addType').modal('hide');
    apiReGameType(uid, gameType, () => {
        createList(1);
    });
}

let fileOptIcon = null;
let robotData = {};

function saveData() {


    let userId = $("#labelUserID").val();

    let lableUID = parseInt($("#lableUID").val() || 0);
    if (lableUID <= 100000 || lableUID >= 999999) {
        Swal.fire('请输入有效的玩家ID')
        return;
    }
    let labelNickname = $("#labelNickname").val();
    if (!labelNickname || labelNickname.length === 0) {
        Swal.fire('请输入玩家昵称')
        return;
    }
    let labelUnion = parseInt($("#labelUnion").val() || 0);
    // if (labelUnion <= 0) {
    //     alert('请输入联盟ID');
    //     return;
    // }
    let winRate = parseInt($("#labelWinRate").val() || 0);
    if (winRate < 0 || winRate > 100) {
        Swal.fire('请输入正确的输赢比例')
        return;
    }
    let ip = $("#labelIP").val();

    if (!isIP(ip)) {
        Swal.fire('请输入正确的IP地址')
        return;
    }

    let location = $("#labelAddress").val();
    let latitude = $("#labelLatitude").val();
    let longitude = $("#labelLongitude").val();
    let robotType = $("#labelType").val();
    let gameType = $("#labelGameType").val();
    robotData = {
        uid: lableUID,
        userId: userId.trim(),
        nickname: getNickName(labelNickname),
        unionID: labelUnion,
        lastLoginIP: ip.trim(),
        location: location.trim(),
        latitude: latitude.trim(),
        gameType: gameType,
        longitude: longitude.trim(),
        winRate: winRate,
        robotType: robotType
    };
    $("#imgArr").uploadFile(fileOptIcon);

}



//启用 停用机器人
function robotBand(uid, isBind) {

    apiRobotBand(uid, isBind, () => {
        $('#robotData').bootstrapTable('refresh', {});
    });

}

function robotReback(uid) {

    apiRebackRobot(uid, () => {
        $('#robotData').bootstrapTable('refresh', {});
    });

}

function addOrderUinon(uid) {

    $("#addUserID").val(uid);
    $("#addUserID").attr("disabled", "true");
    $('#addOrder').modal('show');
}


//将机器人加到联盟中
function addRobotToUnion() {

    let uid = $("#addUserID").val();
    let unionID = $("#addUnionID").val();
    $("#addUserID").val("");
    $("#addUnionID").val("");
    $('#addOrder').modal('hide');
    apiRobotToUnion(uid, unionID, () => {
        $('#robotData').bootstrapTable('refresh', {});
    });

}



$(document).ready(function () {

    $(function () {

        //初始化组件
        fileOptIcon = $("#imgArr").initUpload({
            "uploadUrl": "/file/uploadImage", //上传文件信息地址
            "deleteUrl": "/file/deleteFiles", //删除文件信息地址
            "size": 800, //文件大小限制，单位kb,默认不限制
            "maxFileNumber": 1, //文件个数限制，为整数
            "filelSavePath": "static/uploadcache/", //文件上传地址，后台设置的根目录
            "beforeUpload": null, //在上传前执行的函数
            "autoCommit": false, //文件是否自动上传
            "showSummerProgress": false, //是否显示上传进度
            "fileType": ['png', 'jpg'], //文件类型限制，默认不限制，注意写的是文件后缀
            "originalFileList": [], //初始文件
            "success": (opt, fileList) => {

                robotData.avatar = '/' + fileList[0];
                addNewRobot(robotData, function (data) {
                    let result = data.data;
                    if (result.err) {
                        Swal.fire(result.err);
                    } else {
                        $('#addNew').modal('hide');
                        $.modal({
                            body: '保存成功'
                        });
                        createList(1);
                    }
                })
            },
            "error": function (err) {
                console.error(err);
            }
        });

        //数据表格初始化
        $('#robotData').bootstrapTable({
            striped: true, // 是否显示行间隔色
            pageNumber: 1, // 初始化加载第一页
            pagination: true, // 是否分页
            clickToSelect: true,
            theadClasses: "thead-light", //这里设置表头样式
            sidePagination: 'server', // server:服务器端分页|client：前端分页
            pageSize: 10, // 单页记录数
            pageList: [10, 20, 30],
            dataField: "recordArr",
            buttonsClass: 'light',
            buttonsPrefix: 'btn',
            totalField: "totalCount",
            showRefresh: false, // 刷新按钮
            onPageChange: function (number, size) {
                createList(number, size);
            },
            onPostBody: function () {
                //重新启用弹出层,否则formatter格式化函数返回的html字符串上的tooltip提示不生效
                $('[data-bs-toggle="tooltip"]').each(function (i, el) {
                    new bootstrap.Tooltip(el)
                })
            },
            onLoadSuccess: function () {
                //重新启用弹出层,否则formatter格式化函数返回的html字符串上的tooltip提示不生效
                $('[data-bs-toggle="tooltip"]').each(function (i, el) {
                    new bootstrap.Tooltip(el)
                })
            },
            queryParams: function (params) { // 上传服务器的参数
                var temp = { //如果是在服务器端实现分页，limit、offset这两个参数是必须的
                    limit: params.limit, // 每页显示数量
                    offset: params.offset, // SQL语句起始索引
                };
                return temp;
            },
            columns: [{
                checkbox: true,
                align: "center",
                valign: "middle",
            }, {
                title: 'id',
                field: '_id',
                visible: false
            },
            {
                title: 'UID',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'uid',
            }, {
                title: '昵称',
                width: 100,
                align: "center",
                valign: "middle",
                field: 'nickname',

            }, {
                title: '头像',
                field: 'avatar',
                width: 100,
                align: "center",
                valign: "middle",
                formatter: avaterImg
            }, {
                title: 'IP地址',
                width: 200,
                align: "center",
                valign: "middle",
                field: 'lastLoginIP'
            }, {
                title: '地址',
                width: 200,
                align: "center",
                valign: "middle",
                field: 'location'
            }, {
                title: '坐标',
                width: 200,
                align: "center",
                valign: "middle",
                field: 'address'
            }, {
                field: 'createTime',
                align: "center",
                valign: "middle",
                width: 150,
                title: '创建时间',
                formatter: function (value) {
                    return new Date(value).toLocaleString();
                }
            },
            {
                title: '操作',
                width: 200,
                align: "center",
                valign: "middle",
                formatter: option
            }
            ]
        });
        createList();
    })


    // 定义删除、更新按钮
    function robotTypeSet(value, row, index) {

        if (value == 0) {
            return '气氛组';
        } else if (value == 1) {
            return '被动陪打';
        } else if (value == 2) {
            return '主动陪打';
        } else {
            return '暂未设置';
        }
    }

    function gameTypeSet(value, row, index) {

        if (value == 0) {
            return '全部';
        } else if (value == 1) {
            return '炸金花';
        } else if (value == 2) {
            return '牛牛';
        } else if (value == 3) {
            return '跑的快';
        } else if (value == 4) {
            return '三公';
        } else if (value == 5) {
            return '红中麻将';
        } else if (value == 8) {
            return '斗公牛';
        } else if (value == 9) {
            return '十三水';
        } else if (value == 10) {
            return '血战麻将';
        } else if (value == 11) {
            return '关春天';
        } else if (value == 12) {
            return '捞腌菜';
        } else if (value == 13) {
            return '飞小鸡';
        } else if (value == 14) {
            return '三公比金花';
        } else if (value == 15) {
            return '十点半';
        } else if (value == 22) {
            return '冕宁跑得快';
        } else if (value == 28) {
            return '加锅推筒子';
        } else if (value == 30) {
            return '福建十三水';
        } else if (value == 31) {
            return '泉州麻将';
        } else {
            return "未设置"
        }
    }

    function userBind(value, row, index) {
        var htm = "";
        if (value) {
            htm = `<h5><span class="badge badge-pill badge-success">已投放</span></h5>`;
        } else {
            htm = `<h5><span class="badge badge-pill badge-secondary">未投放</span></h5>`;
        }

        return htm;
    }

    // 定义删除、更新按钮
    function avaterImg(value, row, index) {
        var htm = "";
        htm = `<img  style="width: 40px ; height: 40px;"  src="${value}" class="img-thumbnail" >`;
        return htm;
    }

    // 定义删除、更新按钮
    function option(value, row, index) {
        var htm = "";
        htm = `<button type="button" class="btn btn-light"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="修改机器人信息" onClick='robotEdit(${JSON.stringify(row)})'><i class="bi bi-pencil-square fs-5 text-success"></i></button>`;
        // if (row.unionID) {
        //     htm += `<button type="button" class="btn btn-danger btn-sm" onClick="robotReback(${row.uid})">回收</button>`;
        // } else {
        //     htm += `<button type="button" class="btn btn-success btn-sm" onClick="addOrderUinon(${row.uid})">投放</button>`;
        // }
        // if (row.unionID) {
        //     htm += `<button type="button" class="btn btn-danger btn-sm">回收</button>`;
        // } else {
        //     htm += `<button type="button" class="btn btn-success btn-sm">投放</button>`;
        // }

        return htm;
    }

});